package walasp.proto;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Class Which Extends SQLiteOpenHelper to setup and populate the Applications SQLite Database with the appropriate Tables and Lookup Tables
 */
public class TaskDBHelper extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 3;
	private static final String DATABASE_NAME = "TASKS.DB";
	public static final String TASK_TABLE_NAME = "TASKS";

	private static final String TASK_TABLE_CREATE = "CREATE TABLE "
			+ TASK_TABLE_NAME + " (" + Task.TASK_COLUMN_TID
			+ " INTEGER PRIMARY KEY," + Task.TASK_COLUMN_PARENTTID
			+ " INTEGER REFERENCES TID ," + Task.TASK_COLUMN_TASKNAME
			+ " TEXT NOT NULL," + Task.TASK_COLUMN_TASKCONTENT + " TEXT,"
			+ Task.TASK_COLUMN_CREATIONDATE + " INTEGER, "
			+ Task.TASK_COLUMN_STARTDATE + " INTEGER, "
			+ Task.TASK_COLUMN_DUEDATE + " INTEGER, "
			+ Task.TASK_COLUMN_COMPLTEDDATE + " INTEGER, "
			+ Task.TASK_COLUMN_STATUS + " TEXT REFERENCES STATE, "
			+ Task.TASK_COLUMN_PRIORITY + " INTEGER, "
			+ Task.TASK_COLUMN_CONTACTS + " TEXT) ";
	private static final String STATUS_TABLE_CREATE = "CREATE TABLE STATUS (STATE TEXT PRIMARY KEY)";
	private static final String[] STATUS_TABLE_POPULATE = {
			"INSERT INTO STATUS (STATE) VALUES ('" + Status.ACTIVE + "')",
			"INSERT INTO STATUS (STATE) VALUES ('" + Status.FINISHED + "')",
			"INSERT INTO STATUS (STATE) VALUES ('" + Status.PENDING + "')",
			"INSERT INTO STATUS (STATE) VALUES ('" + Status.CANCELLED + "')" };

	/**
	 * Mandatory Constructor calling super Constructor for SQLiteOpenHelper
	 * @param c 
	 * 			The Context
	 * @return a TaskDBHelper
	*/
	public TaskDBHelper(Context c) {

		super(c, DATABASE_NAME, null, DATABASE_VERSION);

	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(STATUS_TABLE_CREATE);
		for (String b : STATUS_TABLE_POPULATE) {
			db.execSQL(b);
		}
		db.execSQL(TASK_TABLE_CREATE);

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// KILLS OLD DB, UPDATES WITH NEW DB.
		// if (oldVersion < newVersion) {
		db.execSQL("DROP TABLE IF EXISTS " + TASK_TABLE_NAME);
		// onCreate(db);
		// }

	}
}
